/*
 * GPSWater.js
 * 物理量
 */
;
(function (call) {
	var main = {
		baseUrl: CafeJS.CXT,
		mapId: "tjMap",
		playList: null,
		datepicker: null,
		legendpicker: null,
		router: {
			getGPSWaterStationId: '/cimiss-web/api',
            getUparGpsEleInRegionByTime:'/glk/tq/getUparGpsEleInRegionByTime',
			getLatestTime: '/cimiss-web/api',
			getLonLatById:'zhfx/station/queryStationByIds',
			productcfg: "/business/common/json/product.json"
		},
		init: function () {
			this.initView();
		},
		initView: function () {
			var that = this;
			that.initDatePicker();
			that.getLatestTime();
			$.getJSON(that.router.productcfg, function (cfg) {
				that.initProductList(cfg);
			})
		},
		// 获取最新实况时间
		getLatestTime: function () {
			var that = this;
            if($("#userInfo").data("isMatchuser")){
                that.datepicker.setVal('2022-07-26 11:00:00'); 
                return;
            }
			$.ajax({
				url: this.router.getLatestTime,
				type: 'GET',
				data: {
					userId: 'BETJ_xxzx_tjyth',
					pwd: 'xxzx_2000_GXW',
					interfaceId: 'getDataLatestTime',
					dataCode: 'MSIS_UPAR_GPSMET',
					dataFormat: 'json'
				},
				dataType: 'json',
				async: false
			}).done(function (res) {
				if (res.returnMessage === "Query Succeed" && res.DS.length > 0) {
					var date = res.DS[0].Datetime;
					var time = date.substr(0,4)+"-"+ date.substr(4,2)+"-"+ date.substr(6,2)+" "+date.substr(8,2)+":"+date.substr(10,2)+":"+date.substr(12);
					time = new Date(time);
					time.setHours(time.getHours() + 8);
					that.datepicker.setVal(time.format('yyyy-MM-dd hh:00:00'));
				}else{
					alert("接口无法返回，请联系信息中心");
				}
			})
		},
		// 初始化产品列表
		initProductList: function (cfg) {
			var that = this
			var params = {
				container: '.product-content.GPSWater',
				data: cfg.GPSWater,
				isMulti: true,
				eleClick: function (ele, oldEle, selected) {
					var name = ele.ele_name;
					that.clearLayer([ele.type]);
					var pro = {
						name: 'GPS水汽_' + name,
						time: that.calcStartTime(ele),
						bussitype: 'GPSWater',
						ele: ele,
						isGrid: false,
						isSK: true
					}
					if (selected) {
						// 增加产品图层
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
					}
				}
			};
			CafeJS.analysis(params);
		},
		// 初始化时间控件
		initDatePicker: function () {
			var _this = this;
			this.datepicker = CafeJS.Datepicker({
				appendTo: "#datepicker-GPSWater",
				curDate: _this.latestTime,
				type: 3,
				dateFmt: 'yyyy-MM-dd hh',
				dateType: 'H',
				timeInterval: 1,
				call: function () {
					_this.queryMultiEleData();
				}
			});
			$("#datepicker-GPSWater").show();
		},
		// 初始化图例
		initLegentpicker: function (ele, appendTo) {
			var that = this;
			var layers = that.getModels(ele);
			var layerIds = [];
			$.each(layers, function (i, m) {
				layerIds.push(m.id);
			});
			CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth: 400,
				h_legend: 15,
				seq: 'decrease',
				productId: ele.ele_id,
				isShowSlider: false
			});
		},
		// 初始化播放列表
		initPlayList: function (pro) {
			var that = this;
			var startTime = pro.time;

			var layers = this.getModels(pro.ele);
			var interval = pro.ele.interval || 60;
			this.playList = CafeJS.Timeline3({
				appendTo: "#a-m-timeline",
				curDate: startTime,
				type: 1,
				pro: pro,
				dateOpt: {
					dateFmt: 'yyyy-MM-dd hh:mm',
					timeInterval: interval
				},
				timeInterval: interval,
				layers: layers,
				gisId: that.mapId,
				call: function (pro) {
					CafeJS.layerManage.updateLayer(pro);
					var ele = pro.ele;
					that.queryEleData(ele, pro.time);
				},
				getPlayData: function (pro, timeArr) {
					var ele = pro.ele;
					that.queryEleData(ele, timeArr);
				}
			});
		},
		// 查询已选择要素
		queryMultiEleData: function () {
			var that = this;
			var pro, time;
			$(".GPSWater .product-list li.active").each(function (i, ele) {
				pro = $(ele).data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'GPSWater', null, pro.ele_id);
				that.queryEleData(pro, time);
			});
		},
		// 查询要素数据
		queryEleData: function (ele, time) {
			var that = this;
			var element = ele.ele_id;
			if (!element) return;
			
			if (time.indexOf(',') == -1) {
				time = new Date(time);
				//time.setHours(time.getHours() - 8);
				time = time.format('yyyyMMddhh0000');
			}
			var elements = "Station_Name,Station_Id_C,"+ele.key;
			/**var param = {
				"userId":"BETJ_xxzx_tjyth",
				"pwd":"xxzx_2000_GXW",
				"interfaceId":"getUparGpsEleInRegionByTime",
				"adminCodes":120000,
				"elements":elements,
				"times":time,
				"dataFormat":"json",
			}*/
            var param = {
                "time":time,
                "area":'2'
            }
			$.ajax({
				url: that.router.getUparGpsEleInRegionByTime,
				data: param,
				type: "GET",
				dataType: 'json',
				success: function (res) {
                    debugger
					if(res.code == 0 && res.data&& res.data.length>0){
						var stationIdArr = [];
						for(var i=0;i<res.data.length;i++){
							stationIdArr.push(res.data[i].Station_Id_C);
						}
						$.ajax({
							url:that.router.getLonLatById,
							data:{"ids":stationIdArr.join(",")},
							type: "GET",
							dataType: 'json',
							success:function (data) {
								if(data.isSuccess&&data.data){
									var arr = [];
									for(var key in data.data){
										var id = key;
										var station = data.data[key];
                                        if(station){
                                            var val = that.getValByStationId(id,res.data,ele.key);
                                            console.log("id"+id+"  val"+val);
                                            if(val != null && val !== ""&& val !== "999999"){
                                                station["val"] = val;
                                                station["name"] = station.stationName;
                                                arr.push(station);
                                            }
                                        }
										
									}
									var eleType = ele.type;
									var dataArr = {};
									dataArr[0] = {};
									dataArr[0][eleType] = arr;
									var labelObj = {};
									labelObj[eleType] = that.getLabelObj(eleType);
									var dataObj = {
										dataArr: dataArr,
										eleTypes: [eleType],
										statTypes: [0]
									}
									GIS.Station.showElements(that.mapId, dataObj, that.getStatStyleObj(), labelObj, null, null, {'cx': true});
									GIS.Station.eleShowControl(that.mapId, CafeJS.tqfx.toolsBar.getUnActiveStationType(), ['WIND', 'VIS', 'TMP', 'TP', 'RH', 'SP'], 'hide');
									CafeJS.tqfx.statSignControl(CafeJS.tqfx.toolsBar.isActive('statsign'));
									// 站点详情
									GIS.MouseEvent.Bind(that.mapId, that.getStatLayerIds(), null, function(stationInfo) {
										return stationInfo.name;
									});
								}
							}
						})
					} else {
						alert("该时间点无水汽数据");
					}
				}
			})
		},
		//根据站点id，获取值
		getValByStationId:function(id,data,type){
			var val = "";
			for(var i=0;i<data.length;i++){
				if(id === data[i].Station_Id_C){
					val =  data[i][type];
					break;
				}
			}
			if(type === "PRE_PRE_Fore" && val === "999999"){
				val = "";
			}
			return val
		},
		// 获取站点GIS图层id
		getStatLayerIds: function(){
			var layerIds = [];
			$(".GPSWater .product-list li.active").each(function(){
				var eleid = $(this).data("pro").type;
				[0].forEach(function(st){
					layerIds.push(eleid + st+"Stat");
				});
			});
			return layerIds;
		},
		// 获取站点类型样式
		getStatStyleObj: function() {
			var styleObj = {
				minLevel: 0,
				size: 8,
				font: { color: { a: 1, r: 1, g: 0, b: 0 }, xOffset: 0, yOffset: 20, size: '16px', length: 26, width: 8 }
			};
			return {
				//基本站
				0: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
			};
		},
		// 获取要素样式
		getLabelObj: function(eleType) {
			var labelObj = {
				"TEM": { color: { R: 233, G: 40, B: 70, A: 1 }, scolor: "rgb(233,40,70)", lineWidth : 1, offx : -20, offy : 0, size : 16},
				"TP": { color: { R: 50, G: 202, B: 30, A: 1 }, scolor: "rgb(50,202,30)", lineWidth : 1, offx : 20, offy : 0, size : 16},
				"RH": {color : {R : 101, G : 83, B : 215, A : 1}, scolor: "rgb(101,83,215)", lineWidth : 1, offx : 0, offy : -20, size : 16},
			}
			return labelObj[eleType];
		},
		// 增加产品图层
		addLayerManage: function (pro) {
			var that = this;
			if (CafeJS.layerManage) {
				CafeJS.layerManage.addLayer(pro);
			} else {
				CafeJS.layerManage = CafeJS.LayerManage({
					appendTo: "#c-b-layermanage",
					mapId: that.mapId,
					proInfo: pro,
					call: function (pro) {
						CafeJS[pro.bussitype].initPlayList(pro);
					},
					more: function (pro) {
						CafeJS[pro.bussitype].stationView(pro);
					},
					close: function (pro) {
						CafeJS[pro.bussitype].delLayer(pro);
					}
				})
			}
		},
		// 根据时间间隔获取开始时间
		calcStartTime: function (ele) {
			var time = new Date(this.datepicker.getVal());
			switch (ele.interval) {
				case 60:
					time.setMinutes(0);
					break;
			}
			return time.format('yyyy-MM-dd hh:mm');
		},
		// 删除图层后取消要素选择
        delLayer: function(pro) {
        	var eleid = pro.ele.ele_id;
    		$(".GPSWater .product-list li.active").each(function(){
        		if ($(this).data('eleid') == eleid){
        			$(this).click();
        			return false;
        		}
        	})
		},
		// 清除单要素GIS图层
		clearLayer: function (eleid) {
			GIS.Station.eleShowControl(this.mapId, [0], eleid, "delete");
		},
		// 获取要素样式
		getModels: function (ele) {
			var models = [];
			$.each(ele.models.split(","), function (i, m) {
				var layerId = "GPSWater-layer-" + m + "-" + ele.ele_id;
				models.push({
					type: m,
					visible: true,
					uv: false,
					wd: true,
					id: layerId
				});
			});
			return models;
		}
	};
	if (typeof call === 'function') {
		CafeJS.GPSWater = main;
		call(main);
	}

})(function (main) {
	CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'ajax', 'timeLine3'], function () {
		main.init();
	});
});
